<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use app\portal\model\Article;
use app\portal\model\Message;
use app\portal\model\MessageModel;
use cmf\controller\HomeBaseController;
use function Qiniu\json_decode;
use think\Db;
use think\Request;

class ProjectController extends HomeBaseController
{
    public function _initialize()
    {
        parent::_initialize();
    }
    //查看资料
    public function index()
    {
        return $this->fetch('project_list');
    }

    //项目列表
    public function projectList(Request $resquest)
    {
        $parameter = $resquest->param();
        $id = $parameter['post_id'];
        $category_id = Db::name('portal_category_post')->where(['post_id' => $id, 'status' => 1])->value('category_id');
        //判断是否是这个项目的人
        $user_id = session('PORTRL_ID');
        $user_role = Db::name('user')->where('id', $user_id)->field('branch_id,authority')->find();
        if ($user_role['authority'] == 'admin' || $user_role['authority'] == '管理员' || $user_role['authority'] == '总经理')
        {
        }
        else
        {
            if ($user_role['branch_id'] != $category_id)
            {
                $this->error(lang('暂无权限访问此项目!!!'));
            }
        }
        //项目名
        $category = Db::name('portal_category')->where('id', $category_id)->field('id,name,parent_id')->find();
        //查出板块文章
        $plate_name = Db::name('portal_category')->where('id', $category['parent_id'])->value('name');
        $post_id_plate = Db::name('portal_category_post')->where([
            'category_id' => $category['parent_id'],
            'status' => 1,
        ])->value('post_id');
        $plate_whe = [
            'post_status' => 1,
            'is_top' => 1,
            'id' => $post_id_plate,
            'delete_time' => 0,
            'post_title' => $plate_name,
        ];
        $plate = Db::name('portal_post')->where($plate_whe)->field('id,thumbnail,post_excerpt,post_title')->find();

        //查出项目下所有的文章,不包括标题是项目名的
        $post = Db::name('portal_category_post')->where(['category_id' => $category_id, 'status' => 1])->field('post_id')->select();
        $post_res = array();
        foreach ($post as $k => $v)
        {
            $post_res[] = $v['post_id'];
        }
        $project_res = Db::name('portal_post')->where('post_status', 1)->whereNotIn('post_title', $category['name'])->whereIn('id', $post_res)->field('id,thumbnail,post_excerpt,post_title,published_time')->paginate(5, false, ['query' => request()->param()]);
        $this->assign(['project_res' => $project_res, 'plate' => $plate, 'category_name' => $category['name']]);
        $this->assign(['project_list' => $project_res->render()]);

        $article['news'] = (new Article())->where('post_id', $id)->where('pic','<>','')->order('create_time desc')->limit(5)->select();

        $param = $resquest->param();

        session('categroy', $category);
        // 第一种 文章数据
        $whereLayer_1['post_id'] = $id;
        $whereLayer_1['layer'] = 1;
        $whereLayer_1['status'] = 1;
        if (isset($param['layer']) && $param['layer'] == 1)
        {
            foreach ($param as $key => $val)
            {
                if ($key == 'search' && $val !== '')
                {
                    $whereLayer_1['title|author'] = ['LIKE', '%' . $param['search'] . '%'];
                }
                if ($key == 'group_path' && $val !== '')
                {
                    $whereLayer_1['type'] = $param['group_path'];
                }
            }
        }

        // 第二种 文章数据
        $whereLayer_2['post_id'] = $id;
        $whereLayer_2['layer'] = 2;
        $whereLayer_2['status'] = 1;
        if (isset($param['layer']) && $param['layer'] == 2)
        {
            foreach ($param as $key => $val)
            {
                if ($key == 'search' && $val !== '')
                {
                    $whereLayer_2['title|author'] = ['LIKE', '%' . $param['search'] . '%'];
                }
                if ($key == 'group_path' && $val !== '')
                {
                    $whereLayer_2['type'] = $param['group_path'];
                }
            }
        }
        // 第三种文章数据
        $whereLayer_3['post_id'] = $id;
        $whereLayer_3['layer'] = 3;
        $whereLayer_3['status'] = 1;
        if (isset($param['layer']) && $param['layer'] == 3)
        {
            foreach ($param as $key => $val)
            {
                if ($key == 'search' && $val !== '')
                {
                    $whereLayer_3['title|author'] = ['LIKE', '%' . $param['search'] . '%'];
                }
                if ($key == 'group_path' && $val !== '')
                {
                    $whereLayer_3['type'] = $param['group_path'];
                }
            }
        }
        // 第四种文章数据
        $whereLayer_4['post_id'] = $id;
        $whereLayer_4['layer'] = 4;
        $whereLayer_4['status'] = 1;
        if (isset($param['layer']) && $param['layer'] == 4)
        {
            foreach ($param as $key => $val)
            {
                if ($key == 'search' && $val !== '')
                {
                    $whereLayer_4['title|author'] = ['LIKE', '%' . $param['search'] . '%'];
                }
                if ($key == 'group_path' && $val !== '')
                {
                    $whereLayer_4['type'] = $param['group_path'];
                }
            }
        }

        $article['layer_1'] = (new Article())->where($whereLayer_1)->order('create_time desc')->limit(5)->select();

        $article['layer_2'] = (new Article())->where($whereLayer_2)->order('create_time desc')->limit(5)->select();

        $article['layer_3'] = (new Article())->where($whereLayer_3)->order('create_time desc')->limit(5)->select();

        $article['layer_4'] = (new Article())->where($whereLayer_4)->order('create_time desc')->limit(3)->select();

        $this->assign(['article' => $article]);

        return $this->fetch('project:index');
    }

    //项目详情
    public function projectDetails(Request $resquest)
    {
        $parameter = $resquest->param();
        $id = $parameter['post_id'];
        $category_id = Db::name('portal_category_post')->where(['post_id' => $id, 'status' => 1])->value('category_id');
        //项目名
        $category = Db::name('portal_category')->where('id', $category_id)->field('id,name,parent_id')->find();
        //查出板块文章
        $plate_name = Db::name('portal_category')->where('id', $category['parent_id'])->value('name');
        $plate_whe = [
            'post_status' => 1,
            'is_top' => 1,
            'delete_time' => 0,
            'post_title' => $plate_name,
        ];
        $plate = Db::name('portal_post')->where($plate_whe)->field('id,thumbnail,post_excerpt,post_title')->find();
        //对应详情文章
        $post_res = Db::name('portal_post')->where('id', $id)->field('id,user_id,thumbnail,post_excerpt,post_content,post_title,post_hits,published_time')->find();
        $post_res['published_time'] = date('Y-m-d H:i:s', $post_res['published_time']);
        //发布人
        $user_name = Db::name('user')->where('id', $post_res['user_id'])->value('user_login');
        //上一条id
        $previous = Db::name('portal_category_post')->where(['category_id' => $category_id, 'status' => 1])->where('post_id', '<', $id)->field('post_id')->find();
        if (empty($previous))
        {
            $previous_id = '';
        }
        $previous_id = $previous['post_id'];
        //下一条id
        $next = Db::name('portal_category_post')->where(['category_id' => $category_id, 'status' => 1])->where('post_id', '>', $id)->field('post_id')->find();
        if (empty($next))
        {
            $next_id = '';
        }
        $next_id = $next['post_id'];
        $this->assign(['plate' => $plate, 'post_res' => $post_res, 'user_name' => $user_name, 'previous_id' => $previous_id, 'next_id' => $next_id, 'category_name' => $category['name']]);

        return $this->fetch('project_details');
    }
    // 添加文章
    public function add(Request $request)
    {
        if ($request->isPost())
        {
            $param = $this->request->param(); // 获取提交的数据

            if ($param['pic'] === '' && $param['video'] === '')
            {
                $this->success('视频或图片不能为空!');
            }

            $validate = $this->validate($param, '\app\portal\validate\Article'); //校检数据是否正确
            if (true === $validate)
            {
                if (true === $this->addArt($param))
                { // 执行数据添加
                    $this->success('添加成功!', '/break/top', '', 1);
                }
            }
            else
            {
                $this->error($validate);
            }
        }
        return $this->fetch('project:add');
    }
    //查看更多
    public function seeMore()
    {
        $param = $this->request->param();
        $where = ['status' => 1];
        foreach ($param as $key => $val)
        {
            if (($key == 'post_id' || $key == 'layer') && $val == '')
            {
                $this->success('错误!不存在的页面');
            }
            if ($key == 'post_id' || $key == 'layer')
            {
                $where[$key] = $val;
            }
            if ($key == 'search' && $val !== '')
            {
                $where['title|author'] = ['LIKE', '%' . $val . '%'];
            }
            if ($key === 'group_path' && $val !== '')
            {
                $where['type'] = $val;
            }
        }
        $category = Db::name('portal_category')->where('id', $where['post_id'])->field('id,name,parent_id')->find();
        $this->assign('cotegory', $category);
        $seeMore = (new Article())->where($where)->order('create_time desc')->paginate(5, false, [
            'query' => $param,
        ]);
        $layer = request()->param('layer');
        $layerName = '其它';
        if ($layer == 1)
        {
            $layerName = '项目支持';
        }
        if ($layer == 2)
        {
            $layerName = '项目技巧';
        }
        if ($layer == 3)
        {
            $layerName = '行业分析';
        }
        if ($layer == 4)
        {
            $layerName = '其它';
        }
        $this->assign('layerName', $layerName);
        $this->assign('art', $seeMore);
        return $this->fetch('project:seemore');
    }

    //详情简介
    public function details()
    {
        // 获取文章
        $artId = input('id');
        $articleModel = new Article();
        $artData = $articleModel->where('id', $artId)->find();

        if ($artData['status'] == 0)
        {
            $this->error('文章不存在!', '', '', 0);
        }

        // 计算 当前文章是否被浏览用户点过赞
        $userId = session('user.id'); // 获取用户ID
        $zanUser = json_decode($artData['user_zan'], true); // 转码用户点赞
        $is_zan = $zanUser ? in_array($userId, $zanUser) : false;

        //

        $artData['view'] += 1;
        $artData->save();

        //获取当前文章同分类下的 其它资料
        $artData['layer'];
        $where['post_id'] = $artData['post_id'];
        $where['layer'] = 4;
        $otherData = $articleModel->where($where)->order('create_time desc')->limit(4)->select();

        //AdminArticleController.php

        $category = Db::name('portal_category')->where('id', $where['post_id'])->field('id,name,parent_id')->find();
        $this->assign('cotegory', $category);

        //同分类下 随机推荐
        $artRand = $articleModel->where('post_id', $artData['post_id'])->orderRaw('rand()')->limit(4)->select();
        //获取评论信息
        $message = (new MessageModel())->where('art_id', $artData['id'])->select();

        foreach ($message as $key => $val)
        {
            $zanMessageUser = json_decode($val['user_zan'], true);
            $message[$key]['is_zan'] = $zanMessageUser ? in_array($userId, $zanMessageUser) : false;
        }
        //
        $artData['messageCount'] = count($message);

        $layer = $artData['layer'];
        $layerName = '其它';
        if ($layer == 1)
        {
            $layerName = '项目支持';
        }
        if ($layer == 2)
        {
            $layerName = '项目技巧';
        }
        if ($layer == 3)
        {
            $layerName = '行业分析';
        }
        if ($layer == 4)
        {
            $layerName = '其它';
        }

        $this->assign('is_zan', $is_zan);
        $this->assign('layerName', $layerName);
        $this->assign('artData', $artData);
        $this->assign('other', $otherData);
        $this->assign('artRand', $artRand);
        $this->assign('message', $message);
        return $this->fetch('project:details');
    }

    /**
     * 文章添加
     * @param array 数据
     */
    private function addArt($data)
    {
        try {
            $article = new Article();
            $data['type'] = $data['video'] ? 2 : 1; // 设置 视频类型文章 or 普通文章类型
            $user_id = session('PORTRL_ID');
            $data['author'] = Db::name('user')->where('id', $user_id)->field('user_login')->find()['user_login'];
            $result = $article->allowField(true)->save($data);
            if (!empty($result))
            {
                return true;
            }
            return $this->error($article->getError());
        }
        catch (\Exception $e)
        {
            $this->error($e->getMessage());
        }
    }
    // 文章点赞
    public function editzan(Request $request)
    {
        $param = $request->param();
        $userId = session('user.id');
        $articleModel = new Article();
        $artData = $articleModel->where('id', $param['id'])->find();
        $zanUser = json_decode($artData['user_zan'], true);
        if (empty($zanUser))
        {
            $zanUser = [];
            $artData['zan'] += 1;
            array_push($zanUser, $userId);
            $artData['user_zan'] = json_encode($zanUser);
            $artData->save();
            return $this->success('点赞成功!', '', $artData['zan']);
        }
        else if (!in_array($userId, $zanUser))
        {
            $artData['zan'] += 1;
            array_push($zanUser, $userId);
            $artData['user_zan'] = json_encode($zanUser);
            $artData->save();
            return $this->success('点赞成功!', '', $artData['zan']);
        }
        else
        {
            $artData['zan'] -= 1;
            foreach ($zanUser as $key => $val)
            {
                if ($val == $userId)
                {
                    unset($zanUser[$key]);
                }
            }
            $zanUser = array_values($zanUser);
            $artData['user_zan'] = json_encode($zanUser);
            $artData->save();
            return $this->success('取消点赞成功!', '', $artData['zan']);
        }

    }
    // 评论点赞
    public function messagezan(Request $request)
    {
        $param = $request->param();
        $userId = session('user.id');
        $messageModel = new MessageModel();
        $artData = $messageModel->where('id', $param['id'])->find();
        $zanUser = json_decode($artData['user_zan'], true);
        if (empty($zanUser))
        {
            $zanUser = [];
            $artData['zan'] += 1;
            array_push($zanUser, $userId);
            $artData['user_zan'] = json_encode($zanUser);
            $artData->save();
            return $this->success('点赞成功!', '', $artData['zan']);
        }
        else if (!in_array($userId, $zanUser))
        {
            $artData['zan'] += 1;
            array_push($zanUser, $userId);
            $artData['user_zan'] = json_encode($zanUser);
            $artData->save();
            return $this->success('点赞成功!', '', $artData['zan']);
        }
        else
        {
            $artData['zan'] -= 1;
            foreach ($zanUser as $key => $val)
            {
                if ($val == $userId)
                {
                    unset($zanUser[$key]);
                }

            }
            $zanUser = array_values($zanUser);
            $artData['user_zan'] = json_encode($zanUser);
            $artData->save();
            return $this->success('取消点赞成功!', '', $artData['zan']);
        }

        $artData['zan'] += 1;
        $artData->save();
        return $artData['zan'];
    }
    // 评论内容提交
    public function message(Request $request)
    {
        $data['content'] = $request->param('content');
        $data['user_name'] = session('user.user_login');
        $data['art_id'] = $request->param('id');
        $messageModel = new MessageModel();
        if (strlen($data['content']) > 100)
        {
            $this->error('文本超出指定长度:100!!!');
        }
        if ($data['content'] === '')
        {
            $this->error('请输入评论内容!');
        }
        if ($messageModel->save($data))
        {
            $this->success('评论成功!');
        }
        $this->error('未知错误!');
    }
}
